<template>
  <div class="flex-d-col h-100%">
    <breadcrumb />
    <div class="app-main-container h-100% flex">
      <div class="left flex-d-col w-50%">
        <div class="title">
          {{ query.id ? "修改" : "添加" }}题目
          <el-button plain size="small" class="pl-4px pr-4px ml-10px h-18px" @click="back"
            >返回</el-button
          >
        </div>
        <div class="flex h-100% p-30px of-y-overlay">
          <el-form
            ref="RefForm"
            :model="formData"
            label-width="auto"
            class="w-100%"
            :rules="rules"
          >
            <el-form-item label="所属题库" prop="questionBankName">
              <!-- <el-input v-model="formData.name" /> -->
              <div class="bg">
                <span class="mr-10px">{{ formData.questionBankName }}</span>
                <el-button
                  type="primary"
                  plain
                  class="outline"
                  @click="dialogVisible = true"
                  >选择题库</el-button
                >
              </div>
            </el-form-item>
            <el-divider />
            <el-form-item label="来源" prop="regulationNum">
              <!-- <el-input v-model="formData.name" /> -->
              <div class="bg">
                <div class="flex">
                  <div>
                    <span>{{ formData.regulationData?.name }}</span
                    ><br />
                    <span v-show="formData.regulationData?.name"
                      >（发布日期：{{ formData.regulationData?.publishTime }}）</span
                    >
                  </div>
                  <el-button
                    type="primary"
                    plain
                    class="outline"
                    @click="
                      (dialogRegulations.show = true), (dialogRegulations.data = [])
                    "
                    >选择规章或文件</el-button
                  >
                </div>
                <el-input
                  v-show="formData.regulationData?.name"
                  v-model="formData.regulationNum"
                  class="w-200px"
                  size="small"
                  placeholder="请输入"
                >
                  <template #prepend>第</template>
                  <template #append>条</template>
                </el-input>
              </div>
            </el-form-item>
            <el-divider />
            <el-form-item label="类型" prop="category">
              <el-select
                v-model="formData.category"
                placeholder="选择题型"
                clearable
                class="min-w-200px"
              >
                <el-option
                  v-for="item in categoryList"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
            <el-divider />
            <el-form-item label="题型" prop="type">
              <el-select
                v-model="formData.type"
                placeholder="选择题型"
                clearable
                class="min-w-200px"
                @change="changeType"
              >
                <el-option
                  v-for="(item, key) in QuestionTypeEnum"
                  :label="item"
                  :value="parseInt(key)"
                />
              </el-select>
            </el-form-item>
            <el-divider />
            <el-form-item label="题目内容" prop="content">
              <el-input v-model="formData.content" type="textarea" placeholder="请输入" />
            </el-form-item>
            <el-divider />
            <template v-if="formData.type">
              <el-form-item label="题目选项">
                <el-button
                  v-if="formData.type != 3"
                  plain
                  @click="formData.questionOptions.push({})"
                  >添加选项</el-button
                >
                <el-table :data="formData.questionOptions" style="width: 100%">
                  <template v-if="[1, 2, 3, '1', '2', '3'].includes(formData.type)">
                    <el-table-column
                      width="55"
                      v-if="[1, 2, 3, '1', '2', '3'].includes(formData.type)"
                    >
                      <template #default="scope">
                        <el-checkbox
                          @change="
                            [1, 3, '1', '3'].includes(formData.type)
                              ? answerChange(formData.questionOptions, scope.row)
                              : ''
                          "
                          v-model="scope.row.isCorrect"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="选项" width="120">
                      <template #default="scope">
                        <span v-if="formData.type == 3">{{ scope.row.name }}</span>
                        <el-input v-else v-model="scope.row.name"></el-input>
                      </template>
                    </el-table-column>
                  </template>
                  <el-table-column
                    :label="
                      [4, '4'].includes(formData.type)
                        ? '填空内容'
                        : [5, '5'].includes(formData.type)
                        ? '问答内容关键字'
                        : '内容（选中选项即设置为答案）'
                    "
                  >
                    <template #default="scope">
                      <el-input v-model="scope.row.content"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="formData.type != 3"
                    label="操作"
                    show-overflow-tooltip
                    width="80"
                  >
                    <template #default="scope">
                      <el-button
                        type="danger"
                        link
                        @click="formData.questionOptions.splice(scope.$index, 1)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-divider />
            </template>
            <el-form-item label="答案解析">
              <el-input
                v-model="formData.analysis"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
            <el-divider />
            <el-form-item label="适用工种">
              <el-button class="m-b-10px" type="primary" plain @click="getJobType"
                >配置</el-button
              >
              <el-table
                :data="formData.configs"
                style="width: 100%"
                stripe
                header-cell-class-name="table-header"
              >
                <!-- <el-table-column type="selection" width="55" /> -->
                <el-table-column label="工种" prop="jobPostName" />
                <el-table-column label="对应难度" width="90">
                  <template #default="scope">{{
                    radioList.difficulty[scope.row.difficulty]
                  }}</template>
                </el-table-column>
                <el-table-column
                  property="address"
                  label="学习周期"
                  show-overflow-tooltip
                  width="90"
                >
                  <template #default="scope">{{
                    radioList.period[scope.row.period]
                  }}</template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-divider />
            <el-space class="mb-20px">
              <el-button
                v-if="!query.id"
                type="primary"
                @click="save(true)"
                :loading="loading"
                >添加并继续</el-button
              >
              <el-button
                type="primary"
                plain
                class="outline"
                @click="save(false)"
                :loading="loading"
                >{{ query.id ? "保存" : "添加" }}并返回</el-button
              >
              <el-button plain @click="back()">取消</el-button>
            </el-space>
          </el-form>
        </div>
      </div>
      <div class="right flex-d-col flex-1 ml-20px">
        <div class="title">&nbsp;</div>
        <div class="flex-d-col h-100%">
          <vue-pdf-app v-if="pdf" style="height: 100%" :pdf="pdf" />
        </div>
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      class="w-fit! b-rd-20px!"
    >
      <div class="h-500px">
        <organizeQuestionBanks
          :key="dialogVisible"
          :rightShow="true"
          @ac-question-data="(val, arr) => (dialogData = { ...val, ...arr })"
        ></organizeQuestionBanks>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择规章 -->
    <el-dialog
      v-model="dialogRegulations.show"
      :show-close="false"
      :close-on-click-modal="false"
      class="b-rd-20px!"
      :title="dialogRegulations.title"
      width="80%"
    >
      <div class="h-500px">
        <selectRegulations
          :key="dialogRegulations.show"
          :filter="{ isActive: true }"
          @ac-data="
            (data) => {
              dialogRegulations.data = data;
            }
          "
        ></selectRegulations>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="regulationsClose">取消</el-button>
          <el-button type="primary" @click="regulationsConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 选择工种 -->
    <el-dialog
      v-model="dialogJobType.show"
      :show-close="false"
      :close-on-click-modal="false"
      class="b-rd-20px!"
      :title="dialogJobType.title"
      width="80%"
    >
      <div class="h-500px">
        <el-table
          ref="RefJobTypeTable"
          :data="dialogJobType.data"
          max-height="500"
          @selection-change="dialogJobTableChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="jobPostName" label="工种" width="200" />
          <el-table-column prop="difficulty" label="对应难度">
            <template #default="scope">
              <el-radio-group v-model="scope.row.difficulty">
                <el-radio
                  v-for="(item, key) in radioList.difficulty"
                  :value="parseInt(key)"
                >
                  {{ item }}
                </el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="period" label="学习周期">
            <template #default="scope">
              <el-radio-group v-model="scope.row.period">
                <el-radio v-for="(item, key) in radioList.period" :value="parseInt(key)">
                  {{ item }}
                </el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="jobTypeClose">取消</el-button>
          <el-button type="primary" @click="jobTypeConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { ApiGetDictionaryCode } from "@/api/data-dictionary/index";
import { Search } from "@element-plus/icons-vue";
import organizeQuestionBanks from "@/components/organizeQuestionBanks/index.vue";
import selectRegulations from "./components/selectRegulations.vue";
import { QuestionTypeEnum } from "@/enums/QuestionTypeEnum";
import {
  ApiGetJob,
  ApiPostQuestion,
  ApiGetQuestionIdAnswer,
  ApiPutQuestion,
  ApiGetQuestionBankId,
  ApiGetQuestionId,
} from "@/api/resource-management/theory";
import { ApiGetRegulationId } from "@/api/resource-management/regulations";
import { ApiGetfile } from "@/api/file";
import VuePdfApp from "vue3-pdf-app";
import "vue3-pdf-app/dist/icons/main.css";
import { dayjs } from "element-plus";

const route = useRoute();
const router = useRouter();
const loading = ref(false);

const { params, query } = route;
const { path } = params;

// const { visitedViews } = storeToRefs(tagsViewStore);

const categoryList = ref([]);
onMounted(() => {
  ApiGetDictionaryCode().then((res) => {
    if (res.code == 200) {
      categoryList.value = res.data;
    }
  });
  // 题库进入
  if (query.qId) {
    let queryData = JSON.parse(query.data);

    formData.value.questionBankId = queryData.id;
    formData.value.questionBankName = queryData.name;
    formData.value.railwayBureau = queryData.data.railwayBureau;
    formData.value.trainDepotName = queryData.data.trainDepotName;
    formData.value.stationName = queryData.data.stationName;
  }
  // 规章进入
  if (query.rId) {
    ApiGetRegulationId({ id: query.rId }).then((res) => {
      if (res.code == 200) {
        res.data.publishTime = dayjs(res.data.publishTime).format("YYYY-MM-DD");
        formData.value.regulationId = res.data.id;
        formData.value.regulationData = res.data;
      }
    });
    // 根据题目获取题目详情 获取题库
    if (query.id) {
      ApiGetQuestionId({ id: query.id }).then((res) => {
        if (res.code == 200) {
          ApiGetQuestionBankId({ id: res.data.questionBankId }).then((res) => {
            if (res.code == 200) {
              formData.value.questionBankName = res.data.name;
              formData.value.questionBankId = res.data.id;
            }
          });
        }
      });
    }
  }

  // 修改按钮进入
  if (query.id) {
    ApiGetQuestionIdAnswer({ id: query.id }).then((res) => {
      if (res.code == 200) {
        formData.value = {
          railwayBureau: formData.value.railwayBureau,
          trainDepotName: formData.value.trainDepotName,
          stationName: formData.value.stationName,
          questionBankName: res.data.questionBank,
          regulationData: {
            name: res.data.source,
            publishTime: dayjs(res.data.updateDateTime).format("YYYY-MM-DD"),
          },
          regulationId: res.data.regulationId,
          regulationNum: res.data.number,
          category: res.data.questionKind,
          type: res.data.quetionType + 1,
          content: res.data.content,
          questionOptions: res.data.questionOptions.map((e) => {
            return {
              content: e.content,
              isCorrect: e.isCorrect,
              name: e.options,
            };
          }),
          analysis: res.data.topicAnalysis,
          scopeOfApplication: [
            {
              workType: 0,
              difficulty: 0,
              learningCycle: 0,
            },
          ],
          createPerson: res.data.createPerson,
          createDateTime: new Date(),
          updatePerson: res.data.updatePerson,
          updateDateTime: new Date(),
          id: query.id,
        };
        // getFile(formData.value);
      }
    });
  }
});

const formData = ref({
  questionBankId: "",
  questionBankName: "",
  questionOptions: [],
  configs: [],
});
const RefForm = ref(null);
const rules = reactive({
  questionBankName: [{ required: true, message: "请选择题库", trigger: "change" }],
  regulationNum: [{ required: true, message: "请选择并填写第几条", trigger: "change" }],
  category: [{ required: true, message: "请选择类型", trigger: "change" }],
  type: [{ required: true, message: "请选择题型", trigger: "change" }],
  content: [{ required: true, message: "请输入题目内容", trigger: "change" }],
});

const dialogVisible = ref(false);
const dialogData = ref("");
const confirm = () => {
  formData.value.questionBankId = dialogData.value.id;
  formData.value.questionBankName = dialogData.value.questionBank;
  formData.value.railwayBureau = dialogData.value.railwayBureau;
  formData.value.trainDepotName = dialogData.value.trainDepotName;
  formData.value.stationName = dialogData.value.stationName;
  dialogVisible.value = false;
};

const save = (type) => {
  RefForm.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      let n = 1;
      formData.value.questionOptions = formData.value.questionOptions.map((e) => {
        return {
          ...e,
          order: n++,
          isCorrect: [4, 5, "4", "5"].includes(formData.value.type) ? true : e.isCorrect,
        };
      });
      let method = query.id ? ApiPutQuestion : ApiPostQuestion;

      let params = {
        railwayBureau: formData.value.railwayBureau,
        trainDepotName: formData.value.trainDepotName,
        stationName: formData.value.stationName,
        questionBank: formData.value.questionBankName,
        source: formData.value.regulationData.name,
        regulationId: formData.value.regulationId,
        number: formData.value.regulationNum,
        questionKind: formData.value.category,
        quetionType: formData.value.type - 1,
        content: formData.value.content,
        questionOptions: formData.value.questionOptions.map((e) => {
          return {
            content: e.content,
            isCorrect: e.isCorrect,
            options: e.name,
          };
        }),
        topicAnalysis: formData.value.analysis,
        scopeOfApplication: [
          {
            workType: 0,
            difficulty: 0,
            learningCycle: 0,
          },
        ],
        createPerson: "00000000-0000-0000-0000-000000000000",
        createDateTime: new Date(),
        updatePerson: "00000000-0000-0000-0000-000000000000",
        updateDateTime: new Date(),
        id: "00000000-0000-0000-0000-000000000000",
      };
      method(params)
        .then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: "添加成功！",
              type: "success",
            });
            if (type) {
              formData.value = {
                configs: [],
                questionBankId: formData.value.questionBankId,
                questionBankName: formData.value.questionBankName,
                questionOptions: [],
                regulationData: formData.value.regulationData,
                regulationId: formData.value.regulationId,
              };
            } else {
              back();
            }
          }
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

const changeType = (val) => {
  formData.value.questionOptions = [];
  if (val == 3) {
    formData.value.questionOptions = [
      {
        name: "A",
        content: "正确",
        isCorrect: true,
      },
      {
        name: "B",
        content: "错误",
        isCorrect: false,
      },
    ];
  }
};

const pdf = ref("");

// 选择规章
const dialogRegulations = reactive({
  show: false,
  title: "选择规章",
  data: [],
});
const regulationsConfirm = () => {
  if (dialogRegulations.data.length == 0) {
    ElMessage({
      message: "请选择一条数据！",
      type: "warning",
    });
    return;
  }
  formData.value.regulationId = dialogRegulations.data[0].id;
  formData.value.regulationData = JSON.parse(JSON.stringify(dialogRegulations.data[0]));
  getFile(formData.value);
  regulationsClose();
};
const regulationsClose = () => {
  dialogRegulations.show = false;
  dialogRegulations.data = [];
};

// 选择工种
const radioList = {
  difficulty: {
    1: "简单",
    2: "一般",
    3: "困难",
    4: "地狱",
  },
  period: {
    1: "周",
    2: "月",
    3: "季",
    4: "年",
  },
};
const dialogJobType = reactive({
  show: false,
  title: "选择工种",
  data: [],
  ac: [],
});
// const jobList = ref([]);
// ApiGetJob({ MaxResultCount: 999 }).then((res) => {
//   if (res.code == 200) {
//     jobList.value = res.data.items;
//   }
// });
// const getJobType = () => {
//   dialogJobType.data = jobList.value.map((e) => {
//     return {
//       jobPostId: e.id,
//       jobPostName: e.name,
//       difficulty: 1,
//       period: 1,
//     };
//   });
//   dialogJobType.show = true;
// };
const RefJobTypeTable = ref(null);
const getJobType = () => {
  ApiGetJob({ MaxResultCount: 999 }).then((res) => {
    if (res.code == 200) {
      dialogJobType.data = res.data.items.map((e) => {
        let arr = formData.value.configs.filter((el) => el.jobPostId == e.id);

        return {
          jobPostId: e.id,
          jobPostName: e.name,
          difficulty: arr.length > 0 ? arr[0].difficulty : 1,
          period: arr.length > 0 ? arr[0].period : 1,
        };
      });
      dialogJobType.show = true;
      // 默认复选框选中
      nextTick(() => {
        dialogJobType.data.map((e) => {
          formData.value.configs.some((el) => el.jobPostId == e.jobPostId)
            ? RefJobTypeTable.value!.toggleRowSelection(e, undefined)
            : "";
        });
      });
    }
  });
};
const dialogJobTableChange = (val) => {
  dialogJobType.ac = val;
};
const jobTypeConfirm = () => {
  formData.value.configs = JSON.parse(JSON.stringify(dialogJobType.ac));
  jobTypeClose();
};
const jobTypeClose = () => {
  dialogJobType.ac = [];
  dialogJobType.data = [];
  dialogJobType.show = false;
};

const back = () => {
  // tagsViewStore.back();
  router.back();
};

// 获取pdf
const getFile = (data) => {
  if (!data.regulationData?.file?.id) {
    pdf.value = "";
    return;
  }
  ApiGetfile({ id: data.regulationData.file.id }).then((res: any) => {
    const blob = new Blob([res.data], { type: "application/pdf" }); // 保存文件流为 Blob
    pdf.value = URL.createObjectURL(blob); // 转换 Blob 为 URL
  });
};

// 单选
const answerChange = (data, row) => {
  data.forEach((element) => {
    element.isCorrect = false;
  });
  row.isCorrect = true;
};
</script>

<style scope lang="scss">
.border {
  border: 1px solid;
  border-radius: 2px;
}
.app-main-container {
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: bold;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-bottom: 20px;
  }
  .left {
    height: 100%;
    & > .flex {
      background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
      border-radius: 20px 20px 20px 20px;
      border: 1px solid rgba(4, 42, 94, 0.1);
    }
    .bg {
      padding: 10px 20px;
      background: #eff4ff;
      border-radius: 6px 6px 6px 6px;
    }
  }
  .right {
  }
}
</style>
